#include "CRam.h"

CRam::CRam()
{

}
std::string CRam::getData()
{
	char buffer[LINE_MAX]{};
	int fd = open(ramPath.c_str(), O_RDONLY);
	if(fd != -1)
	{

		FILE* stream = fdopen(fd, "r");
		if(!stream)
		{
			perror(ramPath.c_str());
			LOG(ERROR) << "Cannot create stream: " << ramPath;
		}else
		{
			if(!fgets(buffer, LINE_MAX, stream))
			{
				perror(ramPath.c_str());
				LOG(ERROR) << "Cannot read file: " << ramPath;
				return "";
			}
		}
	}else
	{
		perror(ramPath.c_str());
		LOG(ERROR) << "Cannot open file: " << ramPath;
		return "";
	}
	std::string output(buffer);
	std::string parsed = output.substr(9, output.size());
	output.erase(remove_if(output.begin(), output.end(), isspace), output.end());
	std::istringstream iss(parsed);
	int memoryTemp = 0;
	iss >> memoryTemp;
	std::string afterConv = std::to_string(memoryTemp);
	afterConv += " kB";
	return afterConv;
}
std::string CRam::getDataInMb()
{
	char buffer[LINE_MAX]{};
	int fd = open(ramPath.c_str(), O_RDONLY);
	if(fd != -1)
	{

		FILE* stream = fdopen(fd, "r");
		if(!stream)
		{
			perror(ramPath.c_str());
			LOG(ERROR) << "Cannot create stream: " << ramPath;
		}else
		{
			if(!fgets(buffer, LINE_MAX, stream))
			{
				perror(ramPath.c_str());
				LOG(ERROR) << "Cannot read file: " << ramPath;
				return "";
			}
		}
	}else
	{
		perror(ramPath.c_str());
		LOG(ERROR) << "Cannot open file: " << ramPath;
		return "";
	}
	std::string output(buffer);
	std::string parsed = output.substr(9, output.size());
	output.erase(remove_if(output.begin(), output.end(), isspace), output.end());
	std::istringstream iss(parsed);
	int memoryTemp = 0;
	iss >> memoryTemp;
	memoryTemp /= 1024;
	std::string afterConv = std::to_string(memoryTemp);
	afterConv += " Mb";
	close(fd);
	return afterConv;
}
CRam::~CRam()
{


}